package com.hxzy.service.system.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.dto.system.RoleSaveDTO;
import com.hxzy.dto.system.SysRoleDTO;
import com.hxzy.entity.system.SysRole;
import com.hxzy.mapper.system.SysRoleMapper;
import com.hxzy.service.system.SysRoleService;
import com.hxzy.vo.system.HxzyUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Set;

/**
 * 角色实现
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    /**
     * 根据用户ID查询角色值
     * @param userId
     * @return
     */
    @Override
    public Set<String> getOwnRoleKey(Long userId) {
        return this.baseMapper.getOwnRoleKey(userId);
    }

    @Override
    public Set<String> getOwnRoleMenuPerms(Long userId) {
        return this.baseMapper.getOwnRoleMenuPerms(userId);
    }

    @Override
    public IPage<SysRole> search(SysRoleDTO roleDTO) {
        LambdaQueryWrapper<SysRole> queryWrapper=new LambdaQueryWrapper<>();

        //动态sql
        //按角色名称查询
        if(StrUtil.isNotBlank(roleDTO.getRoleName())){
            queryWrapper.like(SysRole::getRoleName, roleDTO.getRoleName());
        }

        //按角色状态查询
        if(roleDTO.getStatus()!=null){
            queryWrapper.eq(SysRole::getStatus, roleDTO.getStatus());
        }

        //拼查询分页对象
        IPage<SysRole> page= PageDTO.of(roleDTO.getPage(), roleDTO.getSize());

        return this.page(page,queryWrapper);
    }

    //多表操作，必须要有事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(RoleSaveDTO roleSaveDTO) {
        SysRole  sysRole=new SysRole();
        BeanUtils.copyProperties(roleSaveDTO, sysRole);

        HxzyUser hxzyUser= (HxzyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysRole.setCreateBy(hxzyUser.getUsername());
        sysRole.setCreateTime(new Date());

        boolean save = this.save(sysRole);
        if(save){
            // 批量新增角色sys_role_menu   foreach
            Long[] owernMenus = roleSaveDTO.getOwernMenus();
            if(owernMenus!=null && owernMenus.length>0){
                this.baseMapper.addBatch(sysRole.getId(),  owernMenus);
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(RoleSaveDTO roleSaveDTO) {
        SysRole  sysRole=new SysRole();
        BeanUtils.copyProperties(roleSaveDTO, sysRole);

        HxzyUser hxzyUser= (HxzyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysRole.setUpdateBy(hxzyUser.getUsername());
        sysRole.setUpdateTime(new Date());

        boolean save = this.updateById(sysRole);

        if(save){
            //先删除 sys_role_menu  根据角色id删除
            this.baseMapper.deleteByRoleId(sysRole.getId());

            // 批量新增角色sys_role_menu   foreach
            Long[] owernMenus = roleSaveDTO.getOwernMenus();
            if(owernMenus!=null && owernMenus.length>0){
                this.baseMapper.addBatch(sysRole.getId(),  owernMenus);
            }
        }
    }

    /**
     * 根据角色名称查询，检查角色名称是否存在
     * @param sysRoleDTO
     * @return
     */
    @Override
    public SysRole getByRoleName(SysRoleDTO sysRoleDTO) {
        LambdaQueryWrapper<SysRole> queryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(sysRoleDTO.getRoleName())){
            queryWrapper.eq(SysRole::getRoleName,sysRoleDTO.getRoleName());
        }
        //修改的情况下剔除角色本身的名称
        if (!ObjectUtils.isEmpty(sysRoleDTO.getId())){
            String roleName=null;
            if (sysRoleDTO.getId()!=null){
                SysRole sysRole=this.getById(sysRoleDTO.getId());
                roleName=sysRole==null?null:sysRole.getRoleName();
            }
            queryWrapper.ne(SysRole::getRoleName,roleName);
        }
        return this.getOne(queryWrapper);
    }

    /**
     * 根据角色权限字符查询，检查权限字符是否存在
     * @param sysRoleDTO
     * @return
     */
    @Override
    public SysRole getByRoleKey(SysRoleDTO sysRoleDTO) {
        LambdaQueryWrapper<SysRole> queryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(sysRoleDTO.getRoleKey())){
            queryWrapper.eq(SysRole::getRoleKey,sysRoleDTO.getRoleKey());
        }
        //修改的情况下剔除角色本身的权限字符
        if (!ObjectUtils.isEmpty(sysRoleDTO.getId())){
            String roleKey = null;
            if (sysRoleDTO.getId()!=null){
                SysRole sysRole=this.getById(sysRoleDTO.getId());
                roleKey=sysRole==null?null:sysRole.getRoleKey();
            }
            queryWrapper.ne(SysRole::getRoleKey,roleKey);
        }
        return this.getOne(queryWrapper);
    }
}
